package com.example.mynewsapp.fragment.video

import android.app.Activity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.mynewsapp.R
import com.example.mynewsapp.activity.DetailVideo
import com.example.mynewsapp.activity.DetailVideo.Companion.DETAIL_VIDEO
import com.example.mynewsapp.adapter.VideoAdapter
import com.example.mynewsapp.fragment.Fragment.country
import com.example.mynewsapp.fragment.Fragment.db
import com.example.mynewsapp.fragment.Fragment.mActivity
import com.example.mynewsapp.fragment.Fragment.video_adapter
import com.example.mynewsapp.model.VideoItem
import com.example.mynewsapp.model.VideoModel
import com.example.mynewsapp.network.ApiInterface
import com.example.mynewsapp.network.Constants.BASE_VIDEO_URL
import com.example.mynewsapp.network.HttpRequest
import com.example.mynewsapp.util.Utils
import com.example.mynewsapp.util.Utils.timeStampToString
import kotlinx.android.synthetic.main.news_view.down_pull_update
import kotlinx.android.synthetic.main.video_view.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

abstract class FragmentVideoBase : Fragment(){

    companion object{
        val life = 36
        val cartoon = 10
        val funny = 20
        val food = 4
        val sport = 18
        val music = 20
        val pet = 26
        val technology = 32
        val film = 8
        val game = 30
    }


    private var his_table = "videoHistory"
    private var favor_table = "videoFavorite"

    abstract fun getItemId():Int

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.video_view, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        generateDummyList()

        down_pull_update.setColorSchemeResources(R.color.colorPrimaryDark)
        down_pull_update.setOnRefreshListener {
            var handler = Handler()
            handler.postDelayed({
                generateDummyList()
                down_pull_update.isRefreshing = false
                refreshSuccess()
            }, 1000)
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as Activity
    }

    private fun init() {
        val list = ArrayList<VideoItem>()

        for (i in 0..10) {
            val image = null
            val title = getString(R.string.loading)
            val desc = getString(R.string.loading)
            val provider = getString(R.string.loading)
            val date = getString(R.string.loading)
            val url = ""
            var like = "no"

            val item = VideoItem(image, title, desc, provider, date, url, like)
            list += item
        }
        onSetList(list)
    }

    private fun generateDummyList(){

        val list = ArrayList<VideoItem>()

        country = Utils.getCountry()

        val apiInterface = HttpRequest.createApi(BASE_VIDEO_URL).create(ApiInterface::class.java)
        val call = apiInterface.getVideo(getItemId())
        call.enqueue(object : Callback<VideoModel> {
            override fun onResponse(call: Call<VideoModel>, response: Response<VideoModel>) {
                if (response.isSuccessful && response.body() != null) {
                    val res = response.body()!!.result
//                    videoImage  videoTitle  videoDesc  videoIcon  videoProvider videoDate  videoUrl  videoLike
                    for (i in response.body()!!.result.indices) {

                        val result = res[i].data.videoContent.videoData

                        val image = result.cover.feed
                        val title = result.title
                        val desc = result.description
                        val provider = result.provider.name
                        val date = timeStampToString(result.date)
                        val url = result.webUrl.raw

                        var like = "no"
                        val cursor = db!!.query(favor_table, null, null, null, null, null, null)
                        while (cursor.moveToNext()) {
                            val url_db = cursor.getString(cursor.getColumnIndex("videoUrl"))
                            if (url_db == url) {
                                like = "yes"
                                break
                            }
                        }
                        cursor.close()

                        val item = VideoItem(image, title, desc, provider, date, url, like)
                        list += item

                    }

                    onSetList(list)

                }
            }

            override fun onFailure(call: Call<VideoModel>, t: Throwable) {
                tips()
            }
        })
    }



    // 设置列表
    private fun onSetList(list: ArrayList<VideoItem>) {

        if (recycler_view==null)return

        recycler_view.layoutManager = LinearLayoutManager(context)
        video_adapter = VideoAdapter(list!!,context!!)
        recycler_view.adapter = video_adapter

        video_adapter?.mOnRecyclerViewItemClick = object :
                VideoAdapter.OnRecyclerViewItemClick {
            override fun OnItemClick(view: View?, content: VideoItem, position: Int) {
                val intent = Intent(context, DetailVideo::class.java)

                ifNewsExist(content)
                addData(content)

                intent.putExtra(DETAIL_VIDEO, content)
                startActivity(intent)
            }

            override fun OnLongClick(view: View?, t: VideoItem, position: Int) {
            }
        }
    }

    private fun addData (content: VideoItem) {
        // videoImage  videoTitle  videoDesc  videoIcon  videoProvider videoDate  videoUrl  videoLike
        if (content.url == "") return
        //创建存放数据的ContentValues对象
        val values = ContentValues()
        values.put("videoImage", content.image)
        values.put("videoTitle", content.title)
        values.put("videoDesc", content.desc)
        values.put("videoProvider", content.provider)
        values.put("videoDate", content.date)
        values.put("videoUrl", content.url)
        values.put("videoLike", content.like)
        //数据库执行插入命令
        db!!.insert(his_table, null, values)

    }

    private fun ifNewsExist (content: VideoItem){
        if (content.url == "") return
        val cursor = db!!.query(his_table, null, null, null, null, null, null)
        while (cursor.moveToNext()) {
            val url = cursor.getString(cursor.getColumnIndex("videoUrl"))
            if (url == content.url) {
                db!!.delete(his_table,"videoUrl=?", arrayOf(url))
                break
            }
        }
        cursor.close() // 关闭游标，释放资源
    }

    private fun tips() {
        if (this.isAdded){
            Toast.makeText(mActivity, getString(R.string.loadFail), Toast.LENGTH_SHORT).show()
        }
    }

    private fun refreshSuccess () {
        if (this.isAdded){
            Toast.makeText(mActivity, getString(R.string.refreshSuccess), Toast.LENGTH_SHORT).show()
        }
    }

}